const Model = require('./index')

class DynamicModel extends Model {
  /**
   * 分页查询动态列表
   * @param {*} pageNo
   * @param {*} pageSize
   * @param {*} conditions
   * @returns
   */
  async findPage ({ pageNo, pageSize, conditions }) {
    const conditionSql = this.generateWhereClause(conditions)
    const sql = `select dynamics.*, user.nickname, article.articleTitle, sc.content as circleContent, u.nickname as focusUsername from dynamics
      left join article on article.id = dynamics.articleId
      left join share_circle sc on sc.id = dynamics.circleId
      left join user u on u.id = dynamics.focusUserId
      left join user on user.id = dynamics.userId ${conditionSql} 
      order by dynamics.createTime desc
      limit ${pageSize} offset ${(pageNo - 1) * pageSize}`
    try {
      const list = await this.db.query(sql)
      const total = await this.total(conditionSql)
      return {
        list,
        total
      }
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 获取动态总数量
   * @param {*} conditionSql
   * @returns
   */
  async total (conditionSql) {
    const sql = `select count(*) as total from dynamics 
    left join user on user.id = dynamics.userId ${conditionSql}`
    try {
      const total = await this.db.query(sql)
      return total[0].total
    } catch (error) {
      throw new Error(error)
    }
  }

  async delete (ids) {
    const sql = `delete from dynamics where id in (${ids.map(id => `'${id}'`).join(',')})`
    try {
      await this.db.query(sql)
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new DynamicModel('dynamics')
